/* This file is part of Find The Mouse.
 *
 * Find The Mouse is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Find The Mouse is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Find The Mouse. If not, see <http://www.gnu.org/licenses/>. */
package com.hello.games;
import java.io.IOException;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.hello.R;
import com.hello.R.color;
import com.hello.R.drawable;
import com.hello.R.id;
import com.hello.R.layout;
import com.hello.R.raw;
import com.hello.R.string;
import com.hello.resources.SoundManager;

public class FindTheBeerGame extends Activity {
	
	private SoundManager mSoundManager;// in order to add sound to buttons
	MediaPlayer MP;// background sound
	
	public void setWallpaper() {
		Drawable wallpaper = WallpaperManager.getInstance(this).getDrawable();
        if (wallpaper == null) {
            try {
                clearWallpaper();
            } catch (IOException e) {
              Toast.makeText(this, e.getMessage(), 3).show();
            }
        } else {
        	wallpaper.setColorFilter(R.color.gray,Mode.DARKEN);
            getWindow().setBackgroundDrawable(wallpaper);
        }
	}
	//Global Variables
	private final int cardIDs[] = new int[]{
			R.id.Card1,
			R.id.Card2,
			R.id.Card3
	};

	private Button card[] = new Button[3];
	private int images[]=new int[3];//which image is behind which card. if image[i]=0 ->behind card[i]=beer image
	private final int imagesIDs[]= new int[]{
			R.drawable.beerheineken64x64,
			R.drawable.elephant64x64,
			R.drawable.giraffe64x64
	};
	private static final int BEERINDEX=0;
	private static final int[][] permutations={
		{ 0,1,2 },
		{0,2,1},
		{1,2,0},
		{1,0,2},
		{2,0,1},
		{2,1,0}
	};
	private boolean drunk=false;
	private int attempt=0;
	private static final int GAME_LIMIT=3; //the number of games allowed
	private static final int DELAY_TIME=1500; //delay time in milliseconds between showing the images and the cards

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gamescreen);
		setWallpaper();

		mSoundManager = new SoundManager();
		mSoundManager.initSounds(getBaseContext());
		mSoundManager.addSound(1, R.raw.comedy_zips_pops_and_bonks);
		mSoundManager.addSound(2, R.raw.sound);

		MP=MediaPlayer.create(getBaseContext(), R.raw.black_paper);
		MP.setLooping(true);
		MP.start();

		OnClickListener cardClick = new OnClickListener() { //This listener is used when a card is clicked.

			
			public void onClick(View v) {
				mSoundManager.playSound(1);
				int pressedCard= v.getId();
				Button b = card[pressedCard];
				b.setBackgroundDrawable(getBaseContext().getResources().getDrawable(imagesIDs[images[pressedCard]]));	
				b.setVisibility(View.VISIBLE);
				attempt++;
				if(images[pressedCard]==BEERINDEX){
					drunk=false;
				}else{
					drunk=true;
				}
				delayShowMessage();

			}
		};
		for (int i = 0; i < cardIDs.length; i++) {
			card[i] = (Button)findViewById(cardIDs[i]);
			card[i].setOnClickListener(cardClick);
			card[i].setId(i);
		}        
		startGame();
	}



	private void delayShowOfCards() { //waits short amount of time before hiding the animals
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() { 
			public void run() { 
				FindTheBeerGame.this.showCards();
			} 
		}, DELAY_TIME);
	}

	public void delayNextStep(){
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() { 
			public void run() { 
				FindTheBeerGame.this.doNextStep();
			} 
		}, DELAY_TIME);
	}

	public void delayShowMessage(){
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() { 
			public void run() { 
				FindTheBeerGame.this.showMessage();
			} 
		}, DELAY_TIME);
	}


	private void startGame() { //Called when the game is started

		showImages();//shows the images of the animals and the beer
		delayShowOfCards();

	}

	@Override
	public boolean onSearchRequested() { 
		return false; //since the search button resets the game, do nothing
	}

	private void showImages(){
		Random rand=new Random();
		int i=rand.nextInt(6);
		images=permutations[i];
		for(int j=0; j<3; j++){
			Button b = card[j];
			b.setBackgroundDrawable(getBaseContext().getResources().getDrawable(imagesIDs[images[j]]));	
			b.setVisibility(View.VISIBLE);
		}
	}


	public void showCards(){
		for (Button b : card) { //make all the buttons visible and change all backgrounds to the card image
			b.setBackgroundDrawable(getBaseContext().getResources().getDrawable(R.drawable.card));	
			b.setVisibility(View.VISIBLE);
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent msg) {
		if ((keyCode == KeyEvent.KEYCODE_MENU) || (keyCode == KeyEvent.KEYCODE_SEARCH)) { //menu or search button pressed

		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		} else { //otherwise, do the key's original action
			super.onKeyDown(keyCode, msg);
		}
		return true;
	}

	public void showMessage() {
		String message="";
		if (!drunk) { //show game won message
			message=getString(R.string.YoureNotDrunkMessage);
			//new AlertDialog.Builder(this).setTitle(getString(R.string.win_title)).setMessage(getString(R.string.YoureNotDrunkMessage)).setPositiveButton(getString(R.string.ok), null).show();
		} else {
			switch (attempt){
			case 1:
				message=getString(R.string.firstFailGameMessage);
				break;
			case 2:
				message=getString(R.string.secondFailGameMessage);
				break;
			case 3:
				message=getString(R.string.youreDrunkMessage);
				break;    			
			}


		}
		android.content.DialogInterface.OnClickListener okClick= new android.content.DialogInterface.OnClickListener() {

			
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				FindTheBeerGame.this.delayNextStep();
			}
		};
		new AlertDialog.Builder(this).setTitle(getString(R.string.lose_title)).setMessage(message).setPositiveButton(getString(R.string.ok), okClick).show();
	}

	public boolean getDrunkOutput(){
		return drunk;

	}

	@Override
	public void finish(){
			MP.stop(); //stops the background music
			super.finish();
		
	}

	public void doNextStep() {
		if(!drunk){
			Intent intent = new Intent();
			setResult(RESULT_OK, intent);
			finish();
		}else if(attempt<GAME_LIMIT){
			startGame();
		}else{
			Intent intent = new Intent();
			setResult(RESULT_CANCELED, intent);
			finish();
		}
	}
}